
package com.tocea.formation.dto;


import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
import org.jdom.xpath.XPath;

import com.thoughtworks.xstream.XStream;
import com.tocea.formation.users.IUser;
import com.tocea.formation.users.UserImpl;

public class UsersDAO implements IDAO<List<IUser>>
{
    
    private static final String XML_FILE_PATH = "src/main/resources/xml/users.xml";
    
    public void save(List<IUser> _o) {
    
        XStream xstream = new XStream();
        xstream.alias("users", List.class);
        xstream.alias("user", UserImpl.class);
        xstream.useAttributeFor("id", String.class);
        xstream.useAttributeFor("password", String.class);
        BufferedWriter writer = null;
        try {
            writer = new BufferedWriter(new FileWriter(new File(XML_FILE_PATH)));
            writer.write(xstream.toXML(_o));
            writer.close();
        } catch (IOException e) {
            System.err.println(e);
            e.printStackTrace();
        } finally {
            // pour s'assurer que le flux est bien fermé
            if (writer != null) {
                try {
                    writer.close();
                } catch (IOException e) {
                    System.err.println(e);
                    e.printStackTrace();
                }
            }
        }
        
    }
    
    public List<IUser> unSerialize() {
    
        BufferedReader reader = null;
        String xml = "";
        String line;
        XStream xstream = new XStream();
        xstream.alias("users", List.class);
        xstream.alias("user", UserImpl.class);
        List<IUser> users = new ArrayList<IUser>();
        try {
            users = (List<IUser>) xstream.fromXML(new FileInputStream(XML_FILE_PATH));
        } catch (FileNotFoundException e) {
            System.err.println(e);
            e.printStackTrace();
        }
        return users;
        
    }
    
    public List<Element>  executeQuery(String _xpathQuery) throws JDOMException, IOException {
    
        // On crée une instance de SAXBuilder
        SAXBuilder sxb = new SAXBuilder();
        org.jdom.Document document = sxb.build(new File(XML_FILE_PATH));
        // On initialise un nouvel élément racine avec l'élément racine du
        // document.
        Element rootElement = document.getRootElement();
        
        XPath xpa = XPath.newInstance(_xpathQuery);
        
        return xpa.selectNodes(rootElement);    
        
    }
}
